package 学习计划.数据结构;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 会玩的洋洋
 * https://leetcode.cn/problems/word-pattern/?envType=study-plan&id=shu-ju-jie-gou-ji-chu&plan=data-structures&plan_progress=cqjfoh6
 */
public class _290_单词规律 {

    /**
     * 执行用时：1ms，内存消耗：39.6MB
     * @param pattern
     * @param s
     * @return
     */
    public boolean wordPattern(String pattern, String s) {
        Map<Character, String> cache = new HashMap<>();
        Map<String, Character> uncache = new HashMap<>();
        String[] strings = s.split(" ");
        int n = pattern.length();
        if (n != strings.length) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            String target = strings[i];
            char temp = pattern.charAt(i);
            if (!cache.containsKey(temp)) {
                cache.put(temp, target);
            }
            if (!uncache.containsKey(target)) {
                uncache.put(target, temp);
            }
            if (!cache.get(temp).equals(target) || !uncache.get(target).equals(temp)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 执行用时：0ms，内存消耗：39.2MB
     * @param pattern
     * @param str
     * @return
     */
    public boolean wordPattern2(String pattern, String str) {
        Map<String, Character> str2ch = new HashMap<>();
        Map<Character, String> ch2str = new HashMap<>();
        int m = str.length();
        int i = 0;
        for (int p = 0; p < pattern.length(); ++p) {
            char ch = pattern.charAt(p);
            if (i >= m) {
                return false;
            }
            int j = i;
            while (j < m && str.charAt(j) != ' ') {
                j++;
            }
            String tmp = str.substring(i, j);
            if (str2ch.containsKey(tmp) && str2ch.get(tmp) != ch) {
                return false;
            }
            if (ch2str.containsKey(ch) && !tmp.equals(ch2str.get(ch))) {
                return false;
            }
            str2ch.put(tmp, ch);
            ch2str.put(ch, tmp);
            i = j + 1;
        }
        return i >= m;
    }

}
